package pkg

import (
	"fmt"
	"gitee.com/wayjin/fabric-extension/cryptoutil"
	"gitee.com/wayjin/fabric-extension/cryptoutil/caclient"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"os"
	"path/filepath"
)

type UserRegInfo struct {
	Name   string `json:"name"`
	Secret string `json:"secret"`
	OrgID  string `json:"orgid"`
	Attr   string
}

func enrollUser(svc Service, ctx *gin.Context) {
	userInfo := UserRegInfo{}
	err := ctx.ShouldBindJSON(&userInfo)
	if err != nil {
		ctx.JSON(400, gin.H{"error": err.Error()})
		return
	}
	org, ok := svc.config.PeerOrgs[userInfo.OrgID]
	if !ok {
		ctx.JSON(500, gin.H{"error": "not found peer orgs"})
		return
	}
	client, err := caclient.NewClient(org.CASpec.Host)
	if err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}
	fmt.Println(filepath.Join(svc.config.CryptoOpt.BasePath, org.Admin.Cert))
	_, err = cryptoutil.LoadKeyStoreFromFile(filepath.Join(svc.config.CryptoOpt.BasePath, org.Admin.Cert),
		filepath.Join(svc.config.CryptoOpt.BasePath, org.Admin.Key), nil)
	if err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}

	userReq := caclient.NewRegisterRequest(userInfo.Name, userInfo.Secret, "org1.example.com", caclient.ID_USER)
	userKs, err := client.RegisterAndEnroll(userReq, nil)
	if err != nil {
		ctx.JSON(500, gin.H{"error": err.Error()})
		return
	}

	prk := cryptoutil.NewPrivateKey(userKs.GetPrivateKey())
	signcertDir := filepath.Join(svc.config.CryptoOpt.KeyStorePath, userInfo.Name, "signcerts")
	keycertDir := filepath.Join(svc.config.CryptoOpt.KeyStorePath, userInfo.Name, "keystore")
	keyBytes, _ := prk.GetBytes([]byte(userInfo.Secret))
	err = os.MkdirAll(signcertDir, 0755)
	//fmt.Println("mkdir ", signcertDir, err)
	err = os.MkdirAll(keycertDir, 0755)
	//fmt.Println("mkdir", keycertDir, err)
	ioutil.WriteFile(filepath.Join(signcertDir, "cert.pem"), userKs.GetSignCert(), 0644)
	ioutil.WriteFile(filepath.Join(keycertDir, prk.FileName()), keyBytes, 0644)
}